package com.xiang.mall.framework.core.config

import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer

/**
 * @author xiangliyou
 * @email xiangliyou1814@mail.yneusoft.com
 * @date 2019-03-06 14:27
 *
 */
@Configuration
class JacksonConfiguration : WebMvcConfigurer {
    @Bean
    open fun getMappingJackson2HttpMessageConverter(): MappingJackson2HttpMessageConverter {
        val mappingJackson2HttpMessageConverter = MappingJackson2HttpMessageConverter()
        val objectMapper = ObjectMapper()

        //设置日期格式
//        objectMapper.dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        //排除序列化中为 null 的值
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)


        //Long 转String类型，否则js丢失精度
        val simpleModule = SimpleModule()
        simpleModule.addSerializer(Long::class.java, ToStringSerializer.instance)

        //支持jdk8新特性
        objectMapper
            .registerModule(ParameterNamesModule())
            .registerModule(Jdk8Module())
            .registerModule(JavaTimeModule())
            .registerModule(simpleModule)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)


        mappingJackson2HttpMessageConverter.objectMapper = objectMapper
        return mappingJackson2HttpMessageConverter
    }

    override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>) {
        converters.add(getMappingJackson2HttpMessageConverter())
    }

}